package com.lemon.blog.system.service.impl;

import com.lemon.blog.system.domain.BlFrontMenu;
import com.lemon.blog.system.domain.vo.MetaVo;
import com.lemon.blog.system.domain.vo.RouterVo;
import com.lemon.blog.system.domain.vo.TreeSelect;
import com.lemon.blog.system.mapper.BlFrontMenuMapper;
import com.lemon.blog.system.service.BlFrontMenuService;
import com.lemon.common.core.constant.Constants;
import com.lemon.common.core.constant.UserConstants;
import com.lemon.common.core.utils.StringUtils;
import com.lemon.common.security.service.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 包名称：com.lemon.blog.service.impl
 * 类名称：BlFrontMenuServiceImpl
 * 类描述：前台菜单业务层处理
 * 创建人：@author huangpeng
 * 创建时间：2022年04月25日 17:12
 */
@Service
public class BlFrontMenuServiceImpl extends BaseServiceImpl<BlFrontMenu> implements BlFrontMenuService {

    @Autowired
    private BlFrontMenuMapper menuMapper;

    @Override
    public List<BlFrontMenu> selectMenuList(BlFrontMenu menu) {
        return menuMapper.selectMenuList(menu);
    }

    @Override
    public List<BlFrontMenu> selectMenuTree() {
        List<BlFrontMenu> menus = menuMapper.selectMenuTreeAll();
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<BlFrontMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (BlFrontMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<BlFrontMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<BlFrontMenu> buildMenuTree(List<BlFrontMenu> menus) {
        List<BlFrontMenu> returnList = new ArrayList<BlFrontMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (BlFrontMenu dept : menus)
        {
            tempList.add(dept.getId());
        }
        for (Iterator<BlFrontMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            BlFrontMenu menu = (BlFrontMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<BlFrontMenu> menus) {
        List<BlFrontMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        Integer result = menuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }

    @Override
    public String checkMenuNameUnique(BlFrontMenu menu) {
        long menuId = StringUtils.isNull(menu.getId()) ? -1L : menu.getId();
        BlFrontMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getId() != menuId)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     * @Title: getRouteName
     * @Description: 获取路由名称
     * @param menu 菜单信息
     * @return: String 路由名称
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:43
     */
    public String getRouteName(BlFrontMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     * @Title: getRouterPath
     * @Description: 获取路由地址
     * @param menu 菜单信息
     * @return: String 路由地址
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:44
     */
    public String getRouterPath(BlFrontMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     * @Title: getComponent
     * @Description: 获取组件信息
     * @param menu 菜单信息
     * @return: String 组件信息
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:44
     */
    public String getComponent(BlFrontMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     * @Title: isMenuFrame
     * @Description: 是否为菜单内部跳转
     * @param menu
     * @return: boolean
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:44
     */
    public boolean isMenuFrame(BlFrontMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     * @Title: isInnerLink
     * @Description: 是否为内链组件
     * @param menu
     * @return: boolean
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:45
     */
    public boolean isInnerLink(BlFrontMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     * @Title: isParentView
     * @Description: 是否为parent_view组件
     * @param menu
     * @return: boolean
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:45
     */
    public boolean isParentView(BlFrontMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     * @Title: getChildPerms
     * @Description: 根据父节点的ID获取所有子节点
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return: List<BlFrontMenu>
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:45
     */
    public List<BlFrontMenu> getChildPerms(List<BlFrontMenu> list, int parentId) {
        List<BlFrontMenu> returnList = new ArrayList<BlFrontMenu>();
        for (Iterator<BlFrontMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            BlFrontMenu t = (BlFrontMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     * @Title: recursionFn
     * @Description: 递归列表
     * @param list
     * @param t
     * @return: void
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:46
     */
    private void recursionFn(List<BlFrontMenu> list, BlFrontMenu t) {
        // 得到子节点列表
        List<BlFrontMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BlFrontMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     * @Title: getChildList
     * @Description: 得到子节点列表
     * @param list
     * @param t
     * @return: List<BlFrontMenu>
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:46
     */
    private List<BlFrontMenu> getChildList(List<BlFrontMenu> list, BlFrontMenu t) {
        List<BlFrontMenu> tlist = new ArrayList<BlFrontMenu>();
        Iterator<BlFrontMenu> it = list.iterator();
        while (it.hasNext())
        {
            BlFrontMenu n = (BlFrontMenu) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     * @Title: hasChild
     * @Description: 判断是否有子节点
     * @param list
     * @param t
     * @return: boolean
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:46
     */
    private boolean hasChild(List<BlFrontMenu> list, BlFrontMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     * @Title: innerLinkReplaceEach
     * @Description: 内链域名特殊字符替换
     * @param path
     * @return: String
     * @throws:
     * @author: huangpeng
     * @Date: 2023/2/26 19:46
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS },
                new String[] { "", "" });
    }
}
